<?php
/*
 * This file is part of the "nimo-l4" package.
 *
 * (c) Enkhbayasgalan Galsandorj <eegii2you@yahoo.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace nimo\domains\car_balance\controllers;


use App;
use BaseController;
use nimo\domains\car_balance\Model\CarMaker;
use Redirect;
use Response;
use Input;
use Request;
use Sentry;
use Session;
use Validator;
use View;
use Config;
use nimo\domains\master\models\Domain;
use nimo\domains\car_balance\Model\CarAuction;
use nimo\domains\car_balance\Model\Customer;
use nimo\domains\car_balance\Model\Ems;
use nimo\domains\car_balance\Model\ReAuction;
use nimo\domains\car_balance\Model\ServiceCompany;
use nimo\domains\car_balance\Model\TransportCompany;
use nimo\domains\car_balance\Model\PurchaseCar;
use nimo\domains\car_balance\Model\Container;

use nimo\domains\car_balance\service\SummaryCalcService;

class MainController extends BaseController {

    public function purchaseCarList()
    {
        $query = new PurchaseCar();

        if(Request::has('reset')) {
            Session::forget('purchase_car_list.filter');
        }
        $lastMonths = array(date("Y-m-01",strtotime("-2 month")),date("Y-m-t"));

        if(Request::isMethod('POST')) {
            // Filter form values to session
            $car_maker = is_null(Input::get('car_maker')) ? '' : Input::get('car_maker');
            Session::put('purchase_car_list.filter.car_maker', $car_maker);
            $car_name = is_null(Input::get('car_name')) ? '' : Input::get('car_name');
            Session::put('purchase_car_list.filter.car_name', $car_name);
            $purchase_date = is_null(Input::get('purchase_date')) ? $lastMonths : explode(' - ',Input::get('purchase_date'));
            Session::put('purchase_car_list.filter.purchase_date', $purchase_date);
            $service_company_id = is_null(Input::get('service_company_id')) ? '0' : Input::get('service_company_id');
            //$service_company = $service_company_id != 0 ? ServiceCompany::find($service_company_id) : null;
            Session::put('purchase_car_list.filter.service_company_id', $service_company_id);
            $customer_id = is_null(Input::get('customer_id')) ? '0' : Input::get('customer_id');
            Session::put('purchase_car_list.filter.customer_id', $customer_id);
            $car_auction_id = is_null(Input::get('car_auction_id')) ? '0' : Input::get('car_auction_id');
            Session::put('purchase_car_list.filter.car_auction_id', $car_auction_id);
            $container_id = is_null(Input::get('container_id')) ? '0' : Input::get('container_id');
            Session::put('purchase_car_list.filter.container_id', $container_id);
            $container_id_cb = is_null(Input::get('container_id_cb')) ? '0' : Input::get('container_id_cb');
            Session::put('purchase_car_list.filter.container_id_cb', $container_id_cb);
            $container_no = is_null(Input::get('container_no')) ? '0' : Input::get('container_no');
            Session::put('purchase_car_list.filter.container_no', $container_no);
            $container_no_cb = is_null(Input::get('container_no_cb')) ? '0' : Input::get('container_no_cb');
            Session::put('purchase_car_list.filter.container_no_cb', $container_no_cb);
            $purchase_car_id = is_null(Input::get('purchase_car_id')) ? '' : Input::get('purchase_car_id');
            Session::put('purchase_car_list.filter.purchase_car_id', $purchase_car_id);
            $chassis_no = is_null(Input::get('chassis_no')) ? '0' : Input::get('chassis_no');
            Session::put('purchase_car_list.filter.chassis_no', $chassis_no);
            $price_from = is_null(Input::get('price_from')) ? '0' : Input::get('price_from');
            Session::put('purchase_car_list.filter.price_from', $price_from);
            $price_to = is_null(Input::get('price_to')) ? '0' : Input::get('price_to');
            Session::put('purchase_car_list.filter.price_to', $price_to);
            $comment = is_null(Input::get('comment')) ? '' : Input::get('comment');
            Session::put('purchase_car_list.filter.comment', $comment);
        } else {
            // Filter values from session
            $car_maker = Session::get('purchase_car_list.filter.car_maker', '');
            $car_name = Session::get('purchase_car_list.filter.car_name', '');
            $purchase_date = Session::get('purchase_car_list.filter.purchase_date', $lastMonths);
            $service_company_id = Session::get('purchase_car_list.filter.service_company_id', '0');
            $customer_id = Session::get('purchase_car_list.filter.customer_id', '0');
            $car_auction_id = Session::get('purchase_car_list.filter.car_auction_id', '0');
            $container_id = Session::get('purchase_car_list.filter.container_id', '');
            $container_id_cb = Session::get('purchase_car_list.filter.container_id_cb', '0');
            $container_no = Session::get('purchase_car_list.filter.container_no', '');
            $container_no_cb = Session::get('purchase_car_list.filter.container_no_cb', '0');
            $purchase_car_id = Session::get('purchase_car_list.filter.purchase_car_id', '');
            $chassis_no = Session::get('purchase_car_list.filter.chassis_no', '0');
            $price_from = Session::get('purchase_car_list.filter.price_from', '0');
            $price_to = Session::get('purchase_car_list.filter.price_to', '0');
            $comment = Session::get('purchase_car_list.filter.comment', '');
        }

        // only for customer
        $user = Sentry::getUser();
        if($user->hasAccess('customer', false)) {
            // login user's  customer id reset
            $customer_id = $user->customer_id;
            $customer = $user;
            Session::put('purchase_car_list.filter.customer_id', $customer_id);
        }

        // Applying filters
        if($car_maker) {
            $query = $query->where('car_maker', '=', $car_maker);
            if($car_name)
                $query = $query->where('car_name', '=', $car_name);
        }
        if(count($purchase_date) >1 )
            $query = $query->whereBetween('purchase_date', array(date('Y-m-d', strtotime($purchase_date[0])),date('Y-m-d', strtotime($purchase_date[1]))));
        if($customer_id != '0')
            $query = $query->where('customer_id', '=', $customer_id);
        if($service_company_id != 0) {
            if($service_company_id == 2)
                $query = $query->where('service_company_id', '=', '2');
            else
                $query = $query->where('service_company_id', '=', '1');
        }
        if($car_auction_id != '0')
            $query = $query->where('auction_name', '=', $car_auction_id);
        if($purchase_car_id)
            $query = $query->where('id', '=', $purchase_car_id);
        if($container_id_cb != '0') {
            $query = $query->where(function($query){
                $query->whereNull('container_id')->orWhere('container_id', '=', '');
            });
        } elseif($container_id != '') {
            $query = $query->where('container_id', '=', $container_id);
        }
        if($container_no_cb != '0') {
            $query = $query->where(function($query){
                $query->whereNull('container_no')->orWhere('container_no', '=', '');
            });
        } elseif($container_no != '') {
            $query = $query->where('container_no', '=', $container_no);
        }
        if(!empty($chassis_no) && $chassis_no != '0')
            $query = $query->where('chasis_no', 'like', "%$chassis_no");
        if($price_from != 0)
            $query = $query->where('purchase_price', '>=', $price_from);
        if($price_to != 0)
            $query = $query->where('purchase_price', '<=', $price_to);
            
        if(!empty($comment)) {
            $query = $query->where('purchase_car_comment', 'like', "%$comment%");
        }
            
        // QUERY ORDER
        $query = $query->orderBy('purchase_date', 'desc');

        $perpage = Request::has('perpage') ? Request::get('perpage') : 30;
        $page = Request::has('page') ? Request::get('page') : 1;
        $count = $query->count();
        $total_page = ($count / $perpage) + (($count % $perpage > 0)? 1: 0);
        $pagination = array('total_page' => $total_page, 'perpage' => $perpage, 'page' => $page);

        $cars = $query->with('customer')->with('vanningCompany')->with('carAuction')->with('serviceCompany')->paginate($perpage);

        $filters = array(
            'car_maker' => $car_maker,
            'car_name' => $car_name,
            'purchase_date' => $purchase_date,
            'customer_id' => $customer_id,
            'service_company_id' => $service_company_id,
            'car_auction_id' => $car_auction_id,
            'purchase_car_id' => $purchase_car_id,
            'container_id' => $container_id,
            'container_id_cb' => $container_id_cb,
            'container_no' => $container_no,
            'container_no_cb' => $container_no_cb,
            'chassis_no' => $chassis_no,
            'price_from' => $price_from,
            'price_to' => $price_to,
            'comment' => $comment,
        );

        $car_makers = array_merge(array(''),CarMaker::orderBy('node_left')->where('node_parent', '=', null)->lists('name2'));

        return View::make('nimo.domains.car_balance.Main.car_list')
            ->with('cars', $cars)
            ->with('filters', $filters)
            ->with('service_company_list', array_merge(array('0' => 'All Service company'), ServiceCompany::lists('name', 'id')))
            ->with('customer_list', array_merge(array('0' => 'All Customer'), Customer::lists('name', 'id')))
            ->with('car_makers', array_combine($car_makers, $car_makers))
            ->with('car_auction_list', array_merge(array('0' => 'All Auction'), CarAuction::lists('name', 'id')))
            ->with('pagination', $pagination)
            ->with('customer', isset($customer) ? $customer : null)
            ;
    }

    public function reAuction($id)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        $car = PurchaseCar::findOrFail($id);

        if(Request::isMethod('POST')) {

            $input = Input::all();
            $validation = Validator::make($input, ReAuction::$rules);

            if ($validation->passes())
            {
                // Redirect to the new re_auction page
                return Redirect::route("car_balance.car.car_show", array('id' => $car->id))->with('success', 'ReAuction created successfully');
            }

            // Redirect to the re_auction create page
            return Redirect::route('car_balance.car.car_show', $car->id)->with('error', 'ReAuction was not created, please try again.');

        }

        return View::make('nimo.domains.car_balance.Main.re_auction')
            ->with('car', $car)
            ->with('service_company_list', array_merge(array('0' => ''), ServiceCompany::lists('name', 'id')))
            ->with('transport_company_list', array_merge(array('0' => ''), TransportCompany::lists('name', 'id')))
            ->with('car_auction_list', array_merge(array('0' => ''), CarAuction::lists('name', 'id')))
        ;
    }

    public function summary()
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        if(Request::isMethod('POST')) {
            // Filter form values to session
            $purchase_date = is_null(Input::get('purchase_date')) ? array() : explode(' to ',Input::get('purchase_date'));
            Session::put('summary.filter.purchase_date', $purchase_date);
            $service_company_id = is_null(Input::get('service_company_id')) ? '0' : Input::get('service_company_id');
            Session::put('summary.filter.service_company_id', $service_company_id);
            $customer_id = is_null(Input::get('customer_id')) ? '0' : Input::get('customer_id');
            Session::put('summary.filter.customer_id', $customer_id);
        } else {
            // Filter values from session
            $purchase_date = Session::get('summary.filter.purchase_date', array());
            $service_company_id = Session::get('summary.filter.service_company_id', '0');
            $customer_id = Session::get('summary.filter.customer_id', '0');
        }

        $query = new PurchaseCar();
        if(count($purchase_date) >1 )
            $query = $query->whereBetween('purchase_date', array(date('Ymd', strtotime($purchase_date[0])),date('Ymd', strtotime($purchase_date[1]))));
        if($customer_id != 0)
            $query = $query->where('hudaldan_avagch_id', '=', $customer_id);
        if($service_company_id != 0)
            $query = $query->where('service_company_id', '=', $service_company_id);

        $cars = $query->get();

        $ems_query = new Ems();
        if(count($purchase_date) >1 )
            $ems_query = $ems_query->whereBetween('send_date', array(date('Ymd', strtotime($purchase_date[0])),date('Ymd', strtotime($purchase_date[1]))));
        $ems_count = $ems_query->count();
        $ems_sum = $ems_count > 0 ? $ems_query->sum('fee_japan') : 0;



        $filters = array(
            'purchase_date' => $purchase_date,
            'customer_id' => $customer_id,
            'service_company_id' => $service_company_id,
        );

        $summary_totals = SummaryCalcService::summary($cars);

        return View::make('nimo.domains.car_balance.Main.summary')
            ->with('cars', $cars)
            ->with('filters', $filters)
            ->with('service_company_list', array_merge(array('0' => ''), ServiceCompany::lists('name', 'id')))
            ->with('customer_list', array_merge(array('0' => ''), Customer::lists('name', 'id')))
            ->with('ems_sum', $ems_sum)
            ->with('summary_totals', $summary_totals)
            ->with('ems_count', $ems_count)
        ;
    }

    public function getDashboard()
    {
        return View::make('nimo.domains.car_balance.Main.dashboard');
    }

    public function display()
    {
        $file = Input::get('file');
        $type = Input::get('type');

        if ($type == 'auction') {
            $path = Config::get('app.uploads.auction').$file;
            header('Content-Type: application/pdf');
        }
        elseif ($type == 'container') {
            $path = Config::get('app.uploads.container').$file;
            header('Content-Type: application/pdf');
        }
        elseif ($type == 'export_cert') {
            $path = Config::get('app.uploads.export_cert').$file;
            header('Content-Type: image/jpg');
        }
        if (!file_exists($path) ) {
            echo "Not found file $file.";
            return;
        }

        header('Content-Disposition: inline; filename="'.basename($path).'"');
        header('Content-Length: ' . filesize($path));
        @readfile($path);
    }
}